<script setup lang="ts">
  import { onUnmounted, PropType, ref, watch } from 'vue'
  import useSparePartApplyPostingForm from '@/services/module/store/useSparePartApplyPostingFormService'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import _ from 'lodash'

  const {
    sparePartApplyPostingForm,
    sparePartApplyPostingLoading,
    saveSparePartApplyPosting,
    resetSparePartApplyPostingForm,
  } = useSparePartApplyPostingForm()

  defineOptions({
    name: 'PostingModal',
  })

  const props = defineProps({
    sparePartApplyDetail: {
      type: Object as PropType<WarehouseAPIResponse.SparePartApplyDetail>,
      required: true,
    },
    messageId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const allQtyInputPopoverVisible = ref(false)
  const visible = defineModel<boolean>({ default: false })

  const allActualQty = ref('')

  const closeDialog = () => {
    visible.value = false
  }

  const onDocumentClick = () => {
    allQtyInputPopoverVisible.value = false
  }

  const onQtyMultipleClick = () => {
    allQtyInputPopoverVisible.value = !allQtyInputPopoverVisible.value
    if (allQtyInputPopoverVisible.value) {
      document.addEventListener('click', onDocumentClick)
    }
  }

  const onQtyMultipleConfirmClick = () => {
    allQtyInputPopoverVisible.value = false
    sparePartApplyPostingForm.value.materialApplyVoList =
      sparePartApplyPostingForm.value.materialApplyVoList.map((item) => {
        item.actualQty = Number(allActualQty.value)
        return item
      })
  }

  const init = () => {
    sparePartApplyPostingForm.value = _.cloneDeep(props.sparePartApplyDetail)
    sparePartApplyPostingForm.value.materialApplyVoList =
      sparePartApplyPostingForm.value.materialApplyVoList.filter((item) => !!item.sapDeliveryNo)
  }

  const onConfirmClick = async () => {
    const res = await saveSparePartApplyPosting(props.messageId)
    if (!res) {
      HMessageBox.error('过账失败，请稍后重试')
      return
    }

    if (res.code !== 20000) {
      HMessageBox.error(res.message)
      return
    }

    HMessage.success('操作成功')
    resetSparePartApplyPostingForm()
    closeDialog()
    emits('update')
  }

  const onFillClick = () => {
    sparePartApplyPostingForm.value.materialApplyVoList =
      sparePartApplyPostingForm.value.materialApplyVoList.map((item) => {
        item.actualQty = item.orderQty || 0
        return item
      })
  }

  onUnmounted(() => {
    document.removeEventListener('click', onDocumentClick)
  })

  watch(visible, (value) => {
    if (value) {
      init()
    }
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    :width="1000"
    unit="px"
    title="过账"
    :loading="sparePartApplyPostingLoading"
    @close="closeDialog"
  >
    <div style="margin-bottom: 8px">
      <h-plain-button @click="onFillClick">填充订单数量到实发数量</h-plain-button>
    </div>
    <el-table
      :max-height="350"
      :data="sparePartApplyPostingForm.materialApplyVoList"
      :border="true"
      :stripe="true"
      :resize="true"
    >
      <!-- 序号 -->
      <el-table-column type="index" label="序号" :align="'center'" fixed="left" width="50" />

      <!-- 配件编号 -->
      <el-table-column label="配件编号" prop="spareCode" width="100" show-overflow-tooltip />

      <!-- 配件名称 -->
      <el-table-column show-overflow-tooltip label="配件名称" prop="spareName" min-width="140" />

      <!-- 申请数量 -->
      <el-table-column width="80" label="申请数量" prop="qty" />

      <!-- 订单数量 -->
      <el-table-column width="80" label="订单数量" prop="orderQty" />

      <!-- 实发数量 -->
      <el-table-column label="实发数量" width="120">
        <template #header>
          <div class="multiple-table-column-header">
            <div class="text">实发数量</div>
            <el-popover :width="196" :visible="allQtyInputPopoverVisible" placement="top">
              <template #reference>
                <h-plain-button :height="22" :padding-lr="4" @click.stop="onQtyMultipleClick">
                  批量
                </h-plain-button>
              </template>

              <div class="all-apply-qty-popover" @click.stop="">
                <el-input
                  v-model.trim.number="allActualQty"
                  style="width: 120px"
                  placeholder="请输入数量"
                />
                <h-plain-button @click="onQtyMultipleConfirmClick">确定</h-plain-button>
              </div>
            </el-popover>
          </div>
        </template>
        <template #default="{ row }">
          <el-input v-model.trim.number="row.actualQty" placeholder="请输入实发数量" />
        </template>
      </el-table-column>

      <!-- 规格 -->
      <el-table-column label="规格" prop="specName" width="120" />

      <!-- 分类 -->
      <el-table-column label="分类" prop="goodsType" width="120" />

      <!-- 单位 -->
      <el-table-column label="单位" prop="spareUnit" width="80" />

      <!-- 单价 -->
      <el-table-column label="单价" prop="price" width="100">
        <template #default="{ row }"> ￥{{ row.price.toFixed(2) }} </template>
      </el-table-column>

      <!-- 金额 -->
      <el-table-column label="金额" width="120">
        <template #default="{ row }"> ￥{{ (row.price * row.qty).toFixed(2) }} </template>
      </el-table-column>

      <!-- 备注 -->
      <el-table-column label="备注" width="160" prop="materialRemark" show-overflow-tooltip />

      <!-- 紧急程度 -->
      <el-table-column label="紧急程度" width="120">
        <template #default="{ row }">
          <template v-if="row.urgency === 1">一般</template>
          <template v-if="row.urgency === 2">紧急</template>
          <template v-if="row.urgency === 3">非常紧急</template>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirmClick">确定</h-button>
      <h-button is-modal @click="closeDialog">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .multiple-table-column-header {
    display: flex;
    align-items: center;
    column-gap: 4px;

    .text {
      white-space: nowrap;
    }
  }

  .all-apply-qty-popover {
    display: flex;
    justify-content: space-between;
  }
</style>
